package com.ww.prodiver.util;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @ClassName:
 * @author:
 * @Description:
 * @Date
 **/

/**
 * 增删改查工具类
 */
public class MongoUtil {
    private static MongoTemplate template = ApplicationContextUtil.getBean(MongoTemplate.class);

    public static <T> void insert(T entity) {
        template.insert(entity);
    }

    public static <T> List<T> findAll(Class<T> clazz) {
        return template.findAll(clazz);
    }

    public static <T> T findOneById(long id, Class<T> clazz) {
        return template.findById(id, clazz);
    }

    //普通分页
    public static <T> List<T> findByPage(int pageNum, int rows, Class<T> clazz) {
        Pageable pageable = PageRequest.of(pageNum-1, rows);
        return template.find(new Query().with(pageable), clazz);
    }

    public static <T> Object getFieldWithOne(T t, String ... fieldNames) {
        Query query = queryBuilder(t, fieldNames);
        return template.findOne(query, t.getClass());
    }

    public static <T> Query queryBuilder(T t, String... fields) {
        Query query = new Query();
        for (Field field : t.getClass().getDeclaredFields()) {
            try {
                field.setAccessible(true);
                Object fieldValue = field.get(t);
                if (fieldValue != null) {
                    query.addCriteria(Criteria.where(field.getName()).is(fieldValue));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            for (String fieldName : fields) {
                query.fields().include(fieldName);
            }
        }
        return query;
    }
}
